package com.example.demo.page.demo

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.demo.args.DetailArgs
import com.example.demo.base.BaseBindingFragment
import com.example.demo.ext.observeWithLifecycle
import com.example.demo.utils.InputMethodUtil
import com.jetinno.coffee.databinding.FragmentDemoBinding
import timber.log.Timber

//测试首页
class DemoFragment : BaseBindingFragment<FragmentDemoBinding, DemoViewModel>() {
    override val viewModel: DemoViewModel by viewModels()
    override fun getViewBinding(): FragmentDemoBinding {
        return FragmentDemoBinding.inflate(layoutInflater)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.btnLogin.setOnClickListener {//登录
            InputMethodUtil.hideSoftInputFromWindow(requireActivity(), view)
            viewModel.sendAction(
                DemoAction.ClickLogin(
                    binding.etUser.text.trim().toString(),
                    binding.etPwd.text.trim().toString()
                )
            )
        }
    }

    override fun observeStateOrEvent(viewModel: DemoViewModel) {
        //界面状态
        viewModel.state.observeWithLifecycle(this) { state ->
            when (state) {
                DemoState.Loading -> {
                    Timber.d("加载中")
                    showLoading()
                }

                is DemoState.LoginSuccess -> {
                    showToast("登录成功")
                    Timber.d("登录成功")
                    dismissLoading()
                    findNavController().navigate(DetailArgs)
                }

                DemoState.Empty -> dismissLoading()
                is DemoState.Error -> {
                    showToast(state.ex)
                    dismissLoading()
                }
            }
        }
        // 界面副作用
        viewModel.effect.observeWithLifecycle(this) { effect ->
            when (effect) {
                is DemoEvent.NavigationToHost -> {
                    findNavController().navigate(DetailArgs)
                    Timber.d("跳转到登录成功界面")
                }
            }
        }
    }

    private fun showToast(msg: String) {
        // 调用 showToast 方法
        Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
    }

    private fun showLoading() {
        binding.progressBar.visibility = View.VISIBLE
    }

    private fun dismissLoading() {
        binding.progressBar.visibility = View.GONE
    }


}